package com.pay.ioopos.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.ConnectivityManager.NetworkCallback;
import android.net.Network;
import android.net.NetworkRequest;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.dongqing.payreport.PayReport;
import com.pay.ioopos.DataFactory;
import com.pay.ioopos.HttpUtil;
import com.pay.ioopos.Utils;
import com.pay.ioopos.sqlite.SettingHelper;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;


public class ReportService extends IntentService {
    private static final String TAG = ReportService.class.getSimpleName();
    private static Handler toastHandler = new Handler();
    private static Toast toast;
    private static boolean inited = false;
    private static NetworkCallback callback;
    private Thread thread;
    private String wx_appid;
    private String wx_mch_id;
    private String wx_sub_mch_id;
    private String wx_timestamp;
    private String wx_nonce_str;
    private String wx_serial_no;
    private String wx_device_category;
    private String wx_device_class;
    private String wx_device_model;
    private String wx_mch_sign;

    public ReportService() {
        super("ReportService");
    }

    public static void startService(Context context) {
        if (DataFactory.getDataStore().getTransKey().equals(SettingHelper.INIT_KEY)) {
            return;
        }
        Intent service = new Intent(context, ReportService.class);
        context.startService(service);
    }

    public static boolean isInited() {
        return inited;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (inited) {
            return;
        }
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (null == callback) {
            callback = new NetworkCallback() {
                @Override
                public void onAvailable(@NonNull Network network) {
                    startInitSdk();
                }

                @Override
                public void onLost(@NonNull Network network) {
                    stopInitSdk();
                }
            };
        } else {
            manager.unregisterNetworkCallback(callback);
        }
        manager.registerNetworkCallback(new NetworkRequest.Builder().build(), callback);
    }

    private void startInitSdk() {
        stopInitSdk();
        thread = new Thread(() -> {
            try {
                initParams();
                initReport();
            } catch (InterruptedException ignore) { }
        });
        thread.start();
    }

    private void stopInitSdk() {
        if (null != thread) {
            thread.interrupt();
        }
    }

    private void initParams() throws InterruptedException {
        while(true) {
            try {
                initSdkParams();
            } catch (Exception e) {
                Log.e(TAG, "微信SDK参数获取失败: ", e);
                toast(String.format("微信SDK参数获取失败：%s", e.getMessage()));
                Thread.sleep(180000);
                continue;
            }
            break;
        }
    }

    private void initSdkParams() throws Exception {
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String sn = Utils.sn();
        String key = DataFactory.getDataStore().getTransKey();
        String serverUrl = DataFactory.getDataStore().getServerUrl();
        String sign = Utils.sha256(sn + timestamp + key);
        JSONObject json = new JSONObject();
        json.put("version", "v2");
        json.put("deviceSn", sn);
        json.put("timestamp", timestamp);
        json.put("sign", sign);
        String jsonString = json.toString();
        jsonString = HttpUtil.post(serverUrl + "/qrpos/api/mch/device/wxsdk", jsonString);
        json = new JSONObject(jsonString);
        if (!json.getString("status").equals("200")) {
            throw new Exception(String.format("[%s]%s", json.getString("status"), json.getString("message")));
        }
        JSONObject result = json.getJSONObject("result");

        wx_appid = result.getString("appid");
        wx_mch_id = result.getString("mch_id");
        if (result.has("sub_mch_id")) {
            wx_sub_mch_id = result.getString("sub_mch_id");
        }
        wx_timestamp = result.getString("timestamp");
        wx_nonce_str = result.getString("nonce_str");
        if (result.has("serial_no")) {
            wx_serial_no = result.getString("serial_no");
        }
        wx_device_category = result.getString("device_category");
        wx_device_class = result.getString("device_class");
        wx_device_model = result.getString("device_model");
        if (result.has("mch_sign")) {
            wx_mch_sign = result.getString("mch_sign");
        }
    }

    private void initReport() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", wx_appid);
        map.put("mch_id", wx_mch_id);
        map.put("sub_mch_id", wx_sub_mch_id);
        map.put("timestamp", Long.parseLong(wx_timestamp));
        map.put("nonce_str", wx_nonce_str);
        map.put("serial_no", wx_serial_no);
        map.put("device_category", Integer.parseInt(wx_device_category));
        map.put("device_class", Integer.parseInt(wx_device_class));
        map.put("device_model", wx_device_model);
        map.put("mch_sign", wx_mch_sign);
        if (null == Looper.myLooper()) {
            Looper.prepare();
        }
        Context context = this;
        PayReport.getInstance(this).initReport(map, new PayReport.InitCallBack() {
            @Override
            public void success() {
                inited = true;
                if (Utils.isApkInDebug(context)) {
                    toast("微信SDK初始化成功");
                }
                try {
                    Thread.sleep(1500000);
                    initReport();
                } catch (InterruptedException ignore) { }
            }

            @Override
            public void failed() {
                if (Utils.isApkInDebug(context)) {
                    toast("微信SDK初始化失败");
                }
                try {
                    Thread.sleep(180000);
                    initReport();
                } catch (InterruptedException ignore) { }
            }
        });

    }

    private void toast(String msg) {
        if (null != toast) {
            toast.cancel();
        }
        if (null == Looper.myLooper()) {
            Looper.prepare();
        }
        toastHandler.post(() -> {
            toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
            toast.show();
        });
    }
}
